package com.bawei.common.view

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import com.bawei.base.view.BaseFragment
import com.bawei.common.event.CustomEvent
import com.bawei.common.vm.BaseViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Author: Jason Zhang
 * Date: 2025/4/22
 * Desc: MVVM模式下的BaseFragment
 */
abstract class BaseMvvmFragment<VDB: ViewDataBinding> : BaseFragment<VDB>() {

    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
        val layoutView = super.onCreateView(inflater, container, savedInstanceState)
        //初始化View
        initViews()
        //加载数据
        loadData()
        //观察数据变化
        observeDataChange()
        //注册EventBus事件总线
        EventBus.getDefault().register(this)
        return layoutView
    }

    protected open fun initViews(){

    }

    protected open fun loadData(){

    }

    protected open fun observeDataChange(){

    }

    /**
     * EventBus接收事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onReceiveEvent(event: CustomEvent?){
        if (event != null && event.target == this.javaClass.simpleName){
            handEvent(event)
        }
    }

    protected open fun handEvent(event: CustomEvent){

    }


    override fun onDestroyView(){
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }



}